import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/authorization', '/ssologin'] // no redirect whitelist
const noTokenList = ['/authorization', '/ssologin', '/autherr']

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  if (noTokenList.includes(to.path)) {
    next()
  } else {
    if (hasToken) {
      if (to.path === '/login') {
        next({ path: '/' })
        NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
      } else {
        const data = await store.dispatch('user/getUserDetail')
        console.log(to.meta)
        if (!data.role_code && (to.path === '/collect' || to.path === '/user')) {
          next({ path: '/401' })
        } else {
          next()
          let rules = [];
          if(data.role_code) rules = [data.role_code];
          const accessRoutes = await store.dispatch('permission/generateRoutes', rules)
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)
        }

      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

// 如果token存在，你要去登录页直接跳到首页，否则判断如果你不是管理员并且你要去权限页面直接让你去401，否则让你下一步，生成权限路由并合并两者路由
// 更改完用户状态之后跳到401，使用回车跳转首页时走到路由里获取用户权限接口已经走不通了，所以在权限接口调通时响应拦截器里直接报错了所以我在回调里进不到401
